﻿//定义js命名空间
Ext.namespace("Fs.Car");

// 商品车信息Form
Fs.Car.CarForm = function () {

    // 定义车辆基本信息
    var CarInfoItems = new Array(
        { name: 'Id', type: 'string' },
        { name: 'TDeport', type: 'string' },
        { name: 'CurrentDep', type: 'string' },
        { name: 'Brand', type: 'string' },
        { name: 'Model', type: 'string' },
        { name: 'Color', type: 'string' },
        { name: 'Engin_ID', type: 'string' },
        { name: 'Frame_ID', type: 'string' },
        { name: 'Prod_Date', type: 'date' },
        { name: 'Miles', type: 'int' },
        { name: 'Appraisal', type: 'float' },
        { name: 'Cost', type: 'float' },
        { name: 'VatID', type: 'string' },
        { name: 'Remark', type: 'string' },
        { name: 'Atm_GJB', type: 'int' },
        { name: 'Atm_BT', type: 'int' },
        { name: 'Atm_SMS', type: 'int' },
        { name: 'Atm_DYQ', type: 'int' },
        { name: 'Atm_BXK', type: 'int' },
        { name: 'Atm_KEY', type: 'int' },
        { name: 'Atm_MAST', type: 'int' },
        { name: 'Atm_WIPER', type: 'int' },
        { name: 'Atm_CERTIFICATE', type: 'int' },
        { name: 'Sal_CUSTNA', type: 'string' },
        { name: 'Sal_CUSTID', type: 'string' },
        { name: 'Sal_CUSTEL', type: 'string' },
        { name: 'Sal_DATE', type: 'date' },
        { name: 'Remark', type: 'string' }
    );

    //对外公用的编辑窗口
    return {

        CarBaseField: CarInfoItems,

        // 商品车信息窗口
        showCarEditFormWinFn: function (formReader, title, itemGridStore, id) {

            var updateEdit = Ext.isDefined(id);
            // 定义获得表单初始加载数据的请求参数
            var formLoadArgs = (updateEdit) ? {
                url: '/Car/GetCarById',
                params: {
                    'Id': id
                },
                waitMsg: '数据加载中...'
            } : null;

            // 金额字段
            var CnMoneyField = function (in_label, in_name) {
                return new Ext.form.CnMoneyField({
                    fieldLabel: in_label,
                    name: in_name,
                    //fieldClass :'field-align_right x-form-field x-form-num-field',
                    width: 150
                });
            };

            var MoneyField_Appraisal = CnMoneyField('估价', 'Appraisal');
            var MoneyField_Cost = CnMoneyField('实际成本', 'Cost');

            var DictCombUtil = Hmis.Util.CommonCombox;
            //定义表单列
            var firstColumn = [
			    DictCombUtil.HmisDictCombo('总仓', 'TDeport'),
			    DictCombUtil.HmisDictCombo('品牌', 'Brand'),
			    DictCombUtil.HmisDictCombo('颜色', 'Color'),
			    DictCombUtil.HmisDictCombo('型号', 'Model'),
                DictCombUtil.HmisDeptCombo('展场', 'CurrentDep'),
			    {
			        fieldLabel: '生产日期',
			        xtype: 'datefield',
			        name: 'Prod_Date',
			        width: 150,
			        format: 'Y年m月d日'
			    }
		    ];

            // 定义表单第二列的组件对象集合
            var secondColumn = [{// 注意 使用时 替换所要表单的第二列组件集合
                fieldLabel: '发动机号<span style="color: red;" >*</span>',
                width: 150,
                name: 'Engin_ID',
                allowBlank: false,
                rvOptions: {
                    url: '/Car/IsFieldExist',
                    params: {
                        'Id': "-1",
                        'FieldName': 'Engin_ID'
                    }
                },
                plugins: [Ext.ux.plugins.RemoteValidator]
            }, {
                fieldLabel: '车架号<span style="color: red;" >*</span>',
                width: 150,
                name: 'Frame_ID',
                allowBlank: false,
                rvOptions: {
                    url: '/Car/IsFieldExist',
                    params: {
                        'Id': "-1",
                        'FieldName': 'Frame_ID'
                    }
                },
                plugins: [Ext.ux.plugins.RemoteValidator]
            }, {
                fieldLabel: '公里数',
                xtype: 'numberfield',
                width: 150,
                name: 'Miles'
            },
		    MoneyField_Appraisal,
		    MoneyField_Cost,
		    {
		        fieldLabel: '增值税号',
		        width: 150,
		        name: 'VatID'
		    }];

            // 定义表单单独列的组件对象集合
            var singleColumn = [
            {
                autoHeight: true,
                layout: 'column',
                columns: 3,
                xtype: 'checkboxgroup',
                id: 'atmGroup',
                anchor: '100%',
                fieldLabel: '附件',
                //itemCls: 'x-check-group-alt',
                items: [{
                    boxLabel: '全选',
                    name: 'Atm_All',
                    inputValue: '1',
                    listeners: {
                        'check': function () {
                            var group = Ext.getCmp('atmGroup');
                            var length = group.items.getCount();
                            var all;
                            if (this.checked == true) {
                                all = true;
                            } else {
                                all = false;
                            }
                            for (i = 0; i < length; i++) {
                                var colItems = group.items.get(i);
                                var jlength = colItems.items.getCount();
                                for (j = 0; j < jlength; j++) {
                                    colItems.items.get(j).setValue(all);
                                }
                            }
                        }
                    }
                }, {
                    boxLabel: '工具包', name: 'Atm_GJB', inputValue: '1'
                }, {
                    boxLabel: '车钥匙', name: 'Atm_KEY', inputValue: '1'
                }, {
                    boxLabel: '备胎', name: 'Atm_BT', inputValue: '1'
                }, {
                    boxLabel: '点烟器', name: 'Atm_DYQ', inputValue: '1'
                }, {
                    boxLabel: '雨刮', name: 'Atm_WIPER', inputValue: '1'
                }, {
                    boxLabel: '天线', name: 'Atm_MAST', inputValue: '1'
                }, {
                    boxLabel: '合格证', name: 'Atm_CERTIFICATE', inputValue: '1'
                }, {
                    boxLabel: '说明书', name: 'Atm_SMS', inputValue: '1'
                }, {
                    boxLabel: '保修卡', name: 'Atm_BXK', inputValue: '1'
                }]
            },
            {
                xtype: 'textarea',
                fieldLabel: '描述',
                name: 'Remark',
                height: 50,
                width: 430
            }];

            // 定义表单 头部固定为两列 末尾单独列 需要改变布局时再修改
            var form = new Ext.FormPanel({
                border: false,
                waitMsgTarget: true,
                labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
                frame: true,
                bodyStyle: 'padding:5px 5px 0',
                reader: formReader, // 注意 这是传入方法的 Ext.data.DataReader 类型
                // 这里的借用表格store的reader属性
                labelAlign: 'right',
                items: [{
                    layout: 'column', // 注意 现在使用的是两列 要是三列或更多
                    // 请改变下面的items
                    // 并在上面定义每个列的组件集合
                    items: [{
                        columnWidth: .5,
                        bodyStyle: 'padding:1px',
                        layout: 'form',
                        defaultType: 'textfield',
                        items: firstColumn
                    }, {
                        columnWidth: .5,
                        bodyStyle: 'padding:1px',
                        layout: 'form',
                        defaultType: 'textfield',
                        items: secondColumn
                    }]
                }, singleColumn],
                buttonAlign: 'center',
                buttons: [new Ext.ux.SubmitBtn({
                    handler: function () {
                        if (form.getForm().isValid()) {
                            form.getForm().submit({
                                url: '/Car/SaveOrUpdate',
                                params: {
                                    'Id': (updateEdit) ? id : ""
                                },
                                success: function (form, action) {
                                    itemGridStore.setDefaultSort('CreateTime', 'DESC');
                                    itemGridStore.load({// 刷新表格
                                        params: {
                                            start: 0,
                                            limit: ALL_PAGESIZE_SETTING
                                        }
                                    });
                                    win.destroy(); // 关闭窗口
                                },
                                failure: function (form, action) {
                                    JsHelper.ShowError(action.result.msg);
                                }
                            }); // formSubmitArgs
                            // 引用之前定义的请求参数变量
                        }
                    }
                }),
                new Ext.Button({
                    minWidth: 80,
                    text: "出库",
                    cls: "x-btn-text-icon",
                    icon: "../Content/icons/cart_remove.png",
                    handler: function () {
                        Fs.Car.CarForm.showCarSellFormWinFn(id);
                    }
                }),
                new Ext.ux.CancelBtn({
                    handler: function () {
                        win.destroy();
                    }
                })]
            });
            // 定义显示窗口
            var win = new Ext.Window({
                title: title,
                iconCls: 'application_form',
                width: 600,
                resizable: false,
                constrain: true,
                autoHeight: true,
                modal: true,
                closeAction: 'close',
                plain: true,
                items: [form]
            });
            win.show();

            //设置值
            form.form.setValues = function (values) {
                if (Ext.isArray(values)) { // array of objects
                    for (var i = 0, len = values.length; i < len; i++) {
                        var v = values[i];
                        var f = this.findField(v.id);
                        if (f) {
                            f.setValue(v.value);
                            if (this.trackResetOnLoad) {
                                f.originalValue = f.getValue();
                            }
                        }
                    }
                } else { // object hash
                    var field, id;
                    for (id in values) {
                        if (id == "JobType" && values[id] == "") {
                            continue;
                        }
                        if (!Ext.isFunction(values[id]) && (field = this.findField(id))) {
                            field.setValue(values[id]);
                            if (this.trackResetOnLoad) {
                                field.originalValue = field.getValue();
                            }
                        }
                    }
                }
                return this;
            }
            if (formLoadArgs) {
                form.load(formLoadArgs); // formLoadArgs 引用之前定义表单数据加载的请求参数变量
            }
        },

        showCarSellFormWinFn: function (id) {

            var firstColumn = [{
                fieldLabel: '客户号',
                width: 150,
                name: 'CustNo'
            }, {
                fieldLabel: '证件类型',
                width: 150,
                name: 'CertTp'
            }, {
                fieldLabel: '证件号码',
                width: 150,
                name: 'CertNo'
            }, {
                fieldLabel: '客户姓名',
                width: 150,
                name: 'CustNa'
            }, {
                fieldLabel: '性别',
                width: 150,
                name: 'Gender'
            }];

            var secondColumn = [{
                fieldLabel: '办公电话',
                width: 150,
                name: 'OffiTL'
            }, {
                fieldLabel: '家庭电话',
                width: 150,
                name: 'HomeTL'
            }, {
                fieldLabel: '手机',
                width: 150,
                name: 'MobiTL'
            }, {
                fieldLabel: '邮编',
                width: 150,
                name: 'MailCD'
            }, {
                fieldLabel: '地址',
                width: 150,
                name: 'MailAD'
            }, {
                fieldLabel: 'EMail',
                width: 150,
                name: 'E_Mail'
            }];

            // 定义表单 头部固定为两列 末尾单独列 需要改变布局时再修改
            var form = new Ext.FormPanel({
                border: false,
                waitMsgTarget: true,
                labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
                frame: true,
                bodyStyle: 'padding:5px 5px 0',
                //reader: BCarInfoFormReader, // 注意 这是传入方法的 Ext.data.DataReader 类型
                // 这里的借用表格store的reader属性
                labelAlign: 'right',
                items: [{
                    layout: 'column', // 注意 现在使用的是两列 要是三列或更多
                    // 请改变下面的items
                    // 并在上面定义每个列的组件集合
                    items: [{
                        columnWidth: .5,
                        bodyStyle: 'padding:1px',
                        layout: 'form',
                        defaultType: 'textfield',
                        items: firstColumn
                    }, {
                        columnWidth: .5,
                        bodyStyle: 'padding:1px',
                        layout: 'form',
                        defaultType: 'textfield',
                        items: secondColumn
                    }]
                }],
                buttonAlign: 'center',
                buttons: [new Ext.ux.SubmitBtn({
                    handler: function () {
                        if (form.getForm().isValid()) {
                            form.getForm().submit({
                                url: '/BCar/SaveOrUpdate',
                                params: {
                                    'AuthorizeUsers': UserCombo.getValue(),
                                    'Id': (updateEdit) ? id : ""
                                },
                                success: function (form, action) {
                                    itemGridStore.setDefaultSort('CreateTime', 'DESC');
                                    itemGridStore.load({// 刷新表格
                                        params: {
                                            start: 0,
                                            limit: ALL_PAGESIZE_SETTING
                                        }
                                    });
                                    win.destroy(); // 关闭窗口
                                },
                                failure: function (form, action) {
                                    JsHelper.ShowError(action.result.msg);
                                }
                            }); // formSubmitArgs
                            // 引用之前定义的请求参数变量
                        }
                    }
                }), new Ext.ux.CancelBtn({
                    handler: function () {
                        win.destroy();
                    }
                })]
            });
            // 定义显示窗口
            var win = new Ext.Window({
                title: '商品车出库',
                iconCls: 'application_form',
                width: 600,
                resizable: false,
                constrain: true,
                autoHeight: true,
                modal: true,
                closeAction: 'close',
                plain: true,
                items: [form]
            });

            win.show();
        },


        // 商品车清单
        showCarListGridPanel: function (itemGridStore, tbar) {
            var tbarDeptComboboxValue = "";
            var tbarDeportComboboxValue = "";

            // 定义filters
            var filters = new Ext.ux.grid.GridFilters({
                encode: true,
                filters: [{
                    dataIndex: 'Brand', // 品牌
                    options: ['丰田', '大众', '本田'],
                    //options : TBarDeptStore.collect('Name'),
                    type: 'list'
                }]
            });
            //查询语句
            filters.buildQuery = function (filters) {
                var p = {}, i, f, root, dataPrefix, key, tmp, len = filters.length;
                if (!this.encode) {
                    for (i = 0; i < len; i++) {
                        f = filters[i];
                        root = [this.paramPrefix, '[', i, ']'].join('');
                        p[root + '[field]'] = f.field;

                        dataPrefix = root + '[data]';
                        for (key in f.data) {
                            p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
                        }
                    }
                } else {
                    tmp = [];
                    for (i = 0; i < len; i++) {
                        f = filters[i];
                        tmp.push(Ext.apply({}, {
                            field: f.field
                        }, f.data));
                    }
                    //加上查询条件
                    if (tbarDeportComboboxValue != "") {
                        tmp.push({
                            field: 'TDeport',
                            type: 'string',
                            value: tbarDeportComboboxValue
                        })
                    }
                    if (tbarDeptComboboxValue != "") {
                        tmp.push({
                            field: 'CurrentDep',
                            type: 'string',
                            value: tbarDeptComboboxValue
                        })
                    }
                    // only build if there is active filter
                    if (tmp.length > 0) {
                        p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
                    }
                }
                return p;
            };

            // 机构Combo Store
            var TBarDeptStore = new Ext.data.JsonStore({
                url: '/InfraHospUser/GetDeptList',
                root: 'data',
                totalProperty: 'total',
                id: 'Id',
                fields: [{
                    name: 'Id',
                    type: 'string'
                }, {
                    name: 'Name',
                    type: 'string'
                }, {
                    name: 'Code',
                    type: 'string'
                }]
            });
            // 添加展场filter
            TBarDeptStore.load({
                callback: function (r) {
                    filters.addFilter({
                        type: 'list',
                        dataIndex: 'CurrentDep',
                        options: JsHelper.GetFilterListData(r, 'Code', 'Name')
                    });
                }
            });

            //字典Store
            var DictStore = function (dictCategory) {
                var dictionaryStore = new Ext.data.JsonStore({
                    url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + dictCategory,
                    root: 'data',
                    totalProperty: 'total',
                    id: 'Code',
                    fields: [{
                        name: 'Id',
                        type: 'string'
                    }, {
                        name: 'Name',
                        type: 'string'
                    }, {
                        name: 'Code',
                        type: 'string'
                    }]
                });
                return dictionaryStore;
            }
            //与筛选有关的字典dictstore
            var DictFilterStore = function (dictCategory, filters, text, value) {
                var dictStore = DictStore(dictCategory);
                dictStore.load({
                    callback: function (r) {
                        filters.addFilter({
                            type: 'list',
                            dataIndex: dictCategory,
                            options: JsHelper.GetFilterListData(r, value, text)
                        });
                    }
                });
                return dictStore;
            }
            //总仓Deport Store
            var TDeportStore = DictFilterStore('TDeport', filters, 'Name', 'Name');
            var BrandStore = DictFilterStore('Brand', filters, 'Name', 'Name');
            var ColorStore = DictFilterStore('Color', filters, 'Name', 'Name');
            var ModelStore = DictFilterStore('Model', filters, 'Name', 'Name');

            // 定义表单 商品车信息Reader
            var CarInfoFormReader = new Ext.data.JsonReader({
                root: 'data',
                fields: CarInfoItems
            });

            // 定义表格选择方式
            var sm = new Ext.grid.CheckboxSelectionModel();

            // 定义Grid表格列
            var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
                header: "总仓",
                dataIndex: 'TDeport',
                width: 50,
                sortable: true
            }, {
                header: "展场",
                dataIndex: 'CurrentDep',
                width: 50,
                sortable: true
            }, {
                header: "品牌",
                dataIndex: 'Brand',
                width: 50,
                sortable: true
            }, {
                header: "型号",
                dataIndex: 'Model',
                sortable: true
            }, {
                header: "颜色",
                width: 50,
                dataIndex: 'Color',
                sortable: true
            }, {
                header: "发动机号",
                dataIndex: 'Engin_ID',
                sortable: true
            }, {
                header: "车架号",
                dataIndex: 'Frame_ID',
                sortable: true
            }, {
                header: "出厂日期",
                width: 90,
                dataIndex: 'Prod_Date',
                sortable: true,
                xtype: 'datecolumn',
                format: 'Y年m月d日'
            }, {
                header: "里程",
                width: 40,
                dataIndex: 'Miles',
                align: 'right',
                renderer: Ext.util.Format.numberRenderer('0,0'),
                sortable: true
            }, {
                header: "估价",
                width: 70,
                dataIndex: 'Appraisal',
                align: 'right',
                renderer: Ext.util.Format.numberRenderer('0,0.00'),
                sortable: true
            }, {
                header: "成本",
                width: 70,
                dataIndex: 'Cost',
                align: 'right',
                renderer: Ext.util.Format.numberRenderer('0,0.00'),
                sortable: true
            }, {
                header: "增值税发票",
                width: 80,
                dataIndex: 'VatID',
                sortable: true
            }, {
                header: "备注信息",
                dataIndex: 'Remark',
                sortable: true
            }]);

            // 设置默认定义表格工具栏
            if (!Ext.isDefined(tbar)) {
                tbar = [{
                    xtype: "tbbutton",
                    minWidth: 80,
                    ref: '../addBtn',
                    text: "添加项",
                    cls: "x-btn-text-icon",
                    icon: "/Content/icons/add.png",
                    handler: function (btn, e) {
                        //showEditFormWinFn(CarInfoFormReader, "添加商品车信息");
                        Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "添加商品车信息", itemGridStore)
                    }
                }, "-", {
                    xtype: "tbbutton",
                    ref: '../delBtn',
                    minWidth: 80,
                    disabled: true,
                    text: "删除项",
                    cls: "x-btn-text-icon",
                    icon: "/Content/icons/delete.png",
                    handler: function (btn, e) {
                        JsHelper.DelConfirm(function (btn) {
                            if (btn == 'yes') {
                                // gridEditor.stopEditing();
                                var s = grid.getSelectionModel().getSelections();
                                for (var i = 0, r; r = s[i]; i++) {
                                    itemGridStore.remove(r);
                                }
                            }
                        });
                    }
                }, "-", {
                    xtype: "tbbutton",
                    minWidth: 80,
                    text: "双击修改项",
                    cls: "x-btn-text-icon",
                    icon: "/Content/icons/pencil.png",
                    disabled: true
                }, '-', '总仓:', {
                    xtype: 'diccombo',
                    id: 'Car_Grid_TBar_TDeport_Combobox',
                    store: DictStore('TDeport'),
                    width: 150,
                    listWidth: 200
                }, "-", ' 展场:', {
                    xtype: 'diccombo',
                    id: 'Car_Gird_TBar_Dept_Combobox',
                    store: TBarDeptStore,
                    width: 150,
                    listWidth: 200
                }, '-', {
                    xtype: "tbbutton",
                    minWidth: 80,
                    text: "查询",
                    cls: "x-btn-text-icon",
                    icon: "/Content/icons/zoom.png",
                    handler: function () {
                        var tbarDeportCombobox = Ext.getCmp("Car_Grid_TBar_TDeport_Combobox");
                        var tbarDeptCombobox = Ext.getCmp("Car_Gird_TBar_Dept_Combobox");
                        if (tbarDeptCombobox.getRawValue() != "") {
                            tbarDeptComboboxValue = tbarDeptCombobox.getRawValue();
                        } else {
                            tbarDeptComboboxValue = "";
                        }
                        if (tbarDeportCombobox.getRawValue() != "") {
                            tbarDeportComboboxValue = tbarDeportCombobox.getRawValue();
                        } else {
                            tbarDeportComboboxValue = "";
                        }
                        var gridStore = grid.getStore();
                        gridStore.load({
                            params: {
                                start: 0,
                                limit: ALL_PAGESIZE_SETTING
                            }
                        });
                    }
                }, "-", {
                    xtype: "tbbutton",
                    minWidth: 80,
                    text: "重置",
                    cls: "x-btn-text-icon",
                    icon: "/Content/icons/arrow_undo.png",
                    handler: function () {
                        var tbarDeptCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Dept_Combobox");
                        var tbarRoleIdCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Role_Combobox");
                        tbarDeptCombobox.clearValue();
                        tbarRoleIdCombobox.clearValue();
                        tbarDeptComboboxValue = "";
                        tbarRoleComboboxValue = "";
                        var gridStore = grid.getStore();
                        gridStore.reload();
                    }
                }];
            }

            // 分页工具栏
            var bbar = new Ext.PagingToolbar({
                displayInfo: true,
                emptyMsg: "没有数据显示",
                displayMsg: "{0}到{1}条，共{2}条",
                store: itemGridStore,
                pageSize: ALL_PAGESIZE_SETTING,
                plugins: [filters]
            });

            // 商品车信息维护表格
            var grid = new Ext.grid.GridPanel({
                enableColumnMove: false,
                sm: sm,
                cm: cm,
                plugins: [filters],
                stripeRows: true,
                frame: true,
                border: true,
                layout: "fit",
                store: itemGridStore,
                loadMask: true,
                tbar: tbar,
                bbar: bbar,
                listeners: {
                    "rowdblclick": function (g, rowIndex, e) {
                        var store = g.getStore()
                        var id = store.getAt(rowIndex).get("Id");
                        alert(rowIndex);
                        alert('store ' + store.getAt(rowIndex).get("Id"));
                        Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "商品车信息", itemGridStore, id)
                    }
                }
            });

            // 控制删除按钮
            grid.getSelectionModel().on('selectionchange', function (sm) {
                grid.delBtn.setDisabled(sm.getCount() < 1);
            });

            itemGridStore.load({
                params: {
                    start: 0,
                    limit: ALL_PAGESIZE_SETTING
                }
            });

            return grid;
        },

        //测试～
        Test: function () {
            alert('Test');
        }
    }
} ();

